import React, { useEffect, useMemo, useState } from "react";
import { Table as AntdTable } from "antd";
import dayjs from "dayjs";
import axios from "axios";
import { CommonComponentProps } from "../Page/dev";



export default function Table({ url, children }: CommonComponentProps) {

    const [loading, setLoading] = useState<boolean>(false);
    const [data, setData] = useState<Array<Record<string, any>>>([]);

    const getData = async () => {
        if (url) {
            setLoading(true);
            const { data } = await axios.get(url);
            setData(data);
            setLoading(false)
        }
    }

    const columns = useMemo(() => {
        return React.Children.map(children, (item: any) => {
            if (item?.props?.type === 'date') {
                return {
                    title: item.props?.title,
                    dataIndex: item.props?.dataIndex,
                    render: (value: any) => value ? dayjs(value).format("YYYY-MM-DD") : null
                }
            } else {
                return {
                    title: item?.props?.title,
                    dataIndex: item?.props?.dataIndex
                }
            }
        })
    }, [children])

    useEffect(() => {
        getData()
    }, [])

    return (
        <AntdTable columns={columns} dataSource={data} pagination={false} rowKey="id" loading={loading} />
    )
}